import 'package:built_collection/built_collection.dart';
import 'package:backend.core/core/domain/entities/devices_to_app_store_user_link.dart';
import 'package:backend.core/core/domain/repositories/devices_to_app_store_user_link_repository/repository.dart';
import 'package:equatable/equatable.dart';
import 'package:mongo_dart/mongo_dart.dart';

part 'dtos/link_dto.dart';

const _kCollectionKey = 'devices_to_app_store_user_links';

class DevicesToAppStoreUserLinkRepositoryImpl implements DevicesToAppStoreUserLinkRepository {
  const DevicesToAppStoreUserLinkRepositoryImpl({
    required Db db,
  }) : _db = db;

  final Db _db;

  @override
  Future<DevicesToAppStoreUserLink?> findLinkByAppStoreUserId({
    required String appStoreUserId,
  }) async {
    final collection = _db.collection(_kCollectionKey);

    final data = await collection.findOne(
      where.eq(_kLinkAppStoreUserIdKey, appStoreUserId),
    );

    if (data == null) {
      return null;
    }

    final link = _LinkDto.fromJson(data).toEntity();

    return link;
  }

  @override
  Future<BuiltList<DevicesToAppStoreUserLink>> findAllLinks() async {
    final collection = _db.collection(_kCollectionKey);

    final linkStream = collection.find();

    final linkJsons = await linkStream.toList();

    final links = linkJsons.map((linkJson) {
      return _LinkDto.fromJson(linkJson).toEntity();
    }).toBuiltList();

    return links;
  }

  @override
  Future<void> upsertLink({
    required DevicesToAppStoreUserLink link,
  }) async {
    final collection = _db.collection(_kCollectionKey);

    final linkJson = _LinkDto.fromEntity(link).toJson();

    await collection.replaceOne(
      where.eq(_kLinkAppStoreUserIdKey, link.appStoreUserId),
      linkJson,
      upsert: true,
    );
  }
}
